<template>
  <div class="app-container">
    <el-drawer
      title="title"
      :visible.sync="drawer"
      :with-header="true"
      :before-close="closeDrawer"
      size="1000px">
      <div slot="title" class="drawer-title">
        <span class="return-icon" @click="closeDrawer">
          <i class="el-icon-back" style="margin-right: 6px;"></i>返回 
        </span>
        <span class="return-icon">镜像ID：{{ this.drawerObj.name }}</span>
      </div>
      <div style="padding: 0 24px 24px 24px;">
        <JsonEditor ref="jsonEditor" v-model="containerInspect"></JsonEditor>
      </div>
    </el-drawer>

    <el-form :model="queryParams" ref="queryParams" :rules="form" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="设备名称" prop="deviceId">
        <el-select clearable v-model="queryParams.deviceId" placeholder="请选择">
          <el-option
              v-for="item in configList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled"
              :remote-method="getListConfig">
              <span style="float: left">{{ item.name }}</span>
              <span :style="{float: 'right', color:  item.colorPicker ? item.colorPicker : '#000000' , fontSize: '13px'}">{{ item.status }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="容器名称" prop="containerName">
        <el-input
          v-model="queryParams.containerName"
          placeholder="请输入容器名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="镜像名称" prop="imageName">
        <el-input
          v-model="queryParams.imageName"
          placeholder="请输入镜像名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="容器状态" prop="status">
        <el-select clearable v-model="queryParams.status" placeholder="请选择">
          <el-option
              v-for="item in dict.type.docker_container_status"
              :key="item.value"
              :label="item.label"
              :value="item.value">
              <span style="float: left">{{ item.label }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['revolution:container:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['revolution:container:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['revolution:container:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['revolution:container:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="containerList" @selection-change="handleSelectionChange">
      <el-table-column label="容器名称" show-overflow-tooltip min-width="35%" align="left" prop="name" >
        <template slot-scope="scope">
        <div class="table-link" @click="showDrawer(scope.row)"> {{ scope.row.name }} </div>
      </template>
      </el-table-column>
      <el-table-column label="镜像名称" show-overflow-tooltip min-width="30%" align="left" prop="imageName" >
        <template slot-scope="scope">
          <i class="el-icon-document-copy" @click="$handleCopy(scope.row.imageName, $event)"></i><span style="margin-left: 10px">{{ scope.row.imageName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="18%" align="left" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.docker_container_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="Cpu使用率" min-width="17%" align="left" prop="cpuUsage" >
        <template slot-scope="scope">
          {{ scope.row.cpuUsage ? scope.row.cpuUsage : "0%" }}
        </template>
      </el-table-column>
      <el-table-column label="内存使用率" min-width="17%" align="left" prop="memoryUsage" >
        <template slot-scope="scope">
          {{ scope.row.memoryUsage ? scope.row.memoryUsage : "0%" }}
        </template>
      </el-table-column>
      <el-table-column label="Ip地址" min-width="23%" align="left" prop="ipAddr[0].ipAddress" />
      <el-table-column label="端口" min-width="35%" align="left" prop="port" >
        <template slot-scope="scope">
          <el-popover width="400" trigger="click" placement="right" visible-arrow="false" >
            <el-tag v-if="scope.row.port.length > 0" slot="reference" type="text" size="small">
              {{ scope.row.port[0] }}
              <i  v-if="scope.row.port.length > 1" class="el-icon-arrow-right el-icon--right"></i>
            </el-tag>
            <div v-for="(item, index) in scope.row.port" :key="index">
              <ul><li>{{ item }}</li></ul>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="运行时长" show-overflow-tooltip min-width="30%" align="left" prop="runtime" />
      <el-table-column label="操作" min-width="46%" align="left" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.status !== 'exited' && scope.row.status !== 'created'"
            size="mini"
            type="text"
            icon="el-icon-caret-right"
            @click="handleStartContainer(scope.row)"
            v-hasPermi="['revolution:container:start']"
          >启动</el-button>
          <el-button :disabled="scope.row.status !== 'running'"
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleStopContainer(scope.row)"
            v-hasPermi="['revolution:container:stop']"
          >停止</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteContainer(scope.row)"
            v-hasPermi="['revolution:container:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改容器对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { listContainer, getContainer, delContainer, addContainer, updateContainer, startContainer, stopContainer } from "@/api/docker/container";
import { listConfig as configListConfig} from "@/api/docker/config";

export default {
  name: "Container",
  dicts: ['docker_status', 'docker_container_status'],
  data() {
    return {
      // 抽屉
      drawer: false,
      // 容器信息
      containerInspect: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // docker 信息表格数据
      configList: [],
      // 容器表格数据
      containerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        deviceId: null,
        containerName: null,
        imageName: null,
        status: null,
      },
      // 表单参数
      form: { 
        deviceId: [
          { required: true, message: "请先选择设备", trigger: "blur" }
        ]
      },
      // 表单校验
      rules: {
      },
      // drawer展示
      drawerObj: {}
    };
  },
  created() {
    this.getListConfig();
  },
  methods: {
    // 开启抽屉
    showDrawer(row) {
      this.$refs["queryParams"].validate(valid => {
        this.drawerObj = row;
        if (valid) {
          getContainer({ 'deviceId' : this.queryParams.deviceId, 'containerId' : row.id }).then(response => {
            this.drawer = true;
            this.containerInspect = response.data;
          });
        }
      });
    },
    /** 关闭抽屉 */
    closeDrawer() {
      this.drawer = false;
      this.drawerObj = {};
      this.containerInspect = {};
    },
    /** 开启容器 */
    handleStartContainer(row) {
      this.$refs["queryParams"].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '容器启动中，请稍候',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          startContainer({ 'deviceId' : this.queryParams.deviceId, 'containerId' : row.id }).then(async (response) => {
            await this._getList();
            loading.close();
            this.$modal.msgSuccess(response.msg);
          }).catch(async (r) => {
            await this._getList();
            loading.close();
            this.$modal.msgError(response.msg);
          });
        }
      })
    },
    /** 停止容器 */
    handleStopContainer(row) {
      this.$refs["queryParams"].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '容器停止中，请稍候',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          stopContainer({ 'deviceId' : this.queryParams.deviceId, 'containerId' : row.id }).then(async (response) => {
            await this._getList();
            loading.close();
            this.$modal.msgSuccess(response.msg);
          }).catch(async (r) => {
            await this._getList();
            loading.close();
            this.$modal.msgError(response.msg);
          });
        }
      })
    },
    /** 删除容器 */
    handleDeleteContainer(row) {
      this.$refs["queryParams"].validate(valid => {
        if (valid) {
          
        }
      })
    },
    /** 查询 容器配置 信息列表 */
    getListConfig() {
      this.loading = false;
      const statusDict = {};
      configListConfig({ pageNum: 1, pageSize: 9999 }).then(response => {
        this.dict.type.docker_status.forEach(d => {
          statusDict[d.value] = d;
        });
        this.configList = response.data.map(r => ({
          ...r, 
          status: statusDict[r.status].label || r.status,
          disabled: r.status == 0 ? true : false,
          colorPicker: statusDict[r.status].raw.colorPicker
        }));
      });
    },
    /** 查询容器列表 */
    getList() {
      this.$refs["queryParams"].validate(valid => {
        if (valid) {
          this.loading = true;
          this._getList();
        }
      });
    },
    /** 查询容器列表 */
    _getList() {
      return new Promise((reslove, reject) => {
        listContainer(this.queryParams).then(response => {
          this.containerList = response.data;
          this.total = response.total;
          this.loading = false;
          reslove();
        }).catch(err => {
          this.loading = false;
          reject();
        })
      }) 
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: null,
        imageName: null,
        status: "0",
        cpuUsage: null,
        memoryUsage: null,
        ipAddr: null,
        port: null,
        runtime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.name)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加容器";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const name = row.name || this.ids
      getContainer(name).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改容器";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.name != null) {
            updateContainer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContainer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const names = row.name || this.ids;
      this.$modal.confirm('是否确认删除容器编号为"' + names + '"的数据项？').then(function() {
        return delContainer(names);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('revolution/container/export', {
        ...this.queryParams
      }, `container_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
  
<style>
  .table-link {
    color: #005eeb;
    font-weight: 700;
    cursor: pointer;
  }
  .drawer-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid rgb(218, 218, 218);
    font-size: 15px;
    font-weight: 500;
  }
  .return-icon {
    cursor: pointer;
    display: flex;
    align-items: center;
    color: #676a6d;
  }
  .el-popover{
    max-height: 400px;
    overflow: auto;
    padding: 0px
  }
</style>